//
//  LBSuperMarketViewController.m
//  loveBeen
//
//  Created by 杨烁 on 2016/11/19.
//  Copyright © 2016年 loveBeen. All rights reserved.
//
#import "LBHomeController.h"
#import "LBHomeFunctionListView.h"
#import "LBTopNextController.h"
#import "DSHTTPClient.h"
#import "AXFNetworkingTools.h"
#import "LBActInfoModel.h"
#import "LBNavBarView.h"

#import "UINavigationBar+Awesome.h"
#import "LBHomeFunctionListView.h"
#import "PYSearch.h"


#import "UINavigationBar+YBZY.h"
#import "UIImage+Convenience.h"
#import "UIImage+YSCutIOutCircle.h"


#import <CoreLocation/CoreLocation.h>
#import "TQLocationConverter.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "SubLBXScanViewController.h"


#import "LBNavigationView.h"

#import "LBActRowsModel.h"
#import "LBImgModel.h"
#import "LBSuperMarketViewController.h"

#import "LBNavigationController.h"

#import "LBSuperMarketViewController.h"


#import "LBSuperMarketProducts.h"
#import "LBSuperMarketCategory.h"
#import "LBGetDataTool.h"
#import "LBLeftTableView.h"
#import "LBRightTableView.h"
#import "LBSuperMarketDetailsVC.h"
#import <SVProgressHUD.h>
#import "LBMinusPlusView.h"
#import "LBRightCell.h"

#import "LBNavigationView.h"

#import "LBNotNetView.h"


// 左 tableview 的宽度



@interface LBSuperMarketViewController ()<
    LBRightTableViewDelegate,
    CAAnimationDelegate,
    LBNotNetViewDelegate
>
// 底层的 bottomview
@property(nonatomic, weak) UIView *bottomView;
// 左 tableview
@property(nonatomic, weak) LBLeftTableView *leftTableView;
// 右 tableview
@property(nonatomic, weak) LBRightTableView *rightTableView;
// 等待菊花
@property(nonatomic, weak) UIActivityIndicatorView *waitActivity;
// 接收模型数组
@property(strong,nonatomic) NSArray<LBSuperMarketCategory *> *marketModelList;

@property(nonatomic, weak) LBNotNetView *errorAlertView;

@end

@implementation LBSuperMarketViewController{

    BOOL _isComplete;

}
-(void)navigation{
    
    LBNavigationView *Naview = [[[NSBundle mainBundle]loadNibNamed:@"LBSupNavigationView" owner:self options:nil]lastObject];
    self.Naview = Naview;
    [Naview.locationbtn.titleLabel setTextColor:[UIColor blackColor]];
    
    [Naview.leftbtn addTarget:self action:@selector(QRScan) forControlEvents:(UIControlEventTouchUpInside)];
    [Naview.rightbtn addTarget:self action:@selector(Seach) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [Naview.leftbtn setImage:[UIImage imageNamed:@"icon_black_scancode"] forState:(UIControlStateNormal)];
    [Naview.rightbtn setImage:[UIImage imageNamed:@"icon_search_black"] forState:UIControlStateNormal];
    [Naview.arrowbtn setImage:[UIImage imageNamed:@"control-down-black"] forState:UIControlStateNormal];
    Naview.leftbackground.alpha = 0;
    Naview.rightbackground.alpha = 0;
    Naview.locationbackground.alpha = 0;
    
    NSString *location = [LBPlusMinusTool sharedPlusMinusTool].location;
    
    [Naview.locationbtn setTitle:[NSString stringWithFormat:@"配送至:%@",location] forState:UIControlStateNormal];
    
    Naview.frame = CGRectMake(0, 0, 375, 64);
    [self.view insertSubview:Naview atIndex:2];
}

-(void)QRScan{
    
    SubLBXScanViewController *QrVc = [[SubLBXScanViewController alloc]init];
    
    
    [self.navigationController pushViewController:QrVc animated:YES];
}

//搜索
-(void)Seach{
    
    NSArray *hotSearchs = @[@"水", @"大闸蟹", @"中秋月饼", @"酸奶",@"啤酒", @"西瓜", @"大荔冬枣", @"贝儿蛋糕", @"方便面", @"酸奶"];
    
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:hotSearchs searchBarPlaceholder:@"Search programming language" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        
        [searchViewController.navigationController pushViewController:[[UIViewController alloc] init] animated:YES];
    }];
    
    searchViewController.hotSearchStyle = PYHotSearchStyleColorfulTag;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleBorderTag;
    //    searchViewController.searchResultShowMode = PYSearchResultShowModeEmbed;
    //    searchViewController.searchSuggestionHidden = YES;
    
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    [self presentViewController:navVC animated:YES completion:nil];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self navigation];
    
   
    // 加载数据
    [self loadData];
    
    // 菊花转
    [SVProgressHUD showWithStatus:@"努力加载中..."];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
//    [SVProgressHUD showImage:[UIImage imageNamed:@"member_bg"] status:@"努力加载中..."];
    
    
    //由于scrollview贴在导航条下 ,系统会自动的有一个64的间距
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animate:) name:Animate object:nil];
}

#pragma mark - leftRow 初始化
- (instancetype)init{
    self = [super init];
    
    self.leftRow = 0;

    return self;
}

// 接收到动画通知后执行的方法
- (void)animate:(NSNotification *)notification{

    NSDictionary *dict = notification.userInfo;
    
    LBRightCell *rightCell = dict[@"mpView"];
    
    
    
    UIImageView *iconView = dict[@"img"];
    
    [self addProductAnimationWithCell:rightCell imgView:iconView];

}


// 产品图片动画方法
- (void)addProductAnimationWithCell:(LBRightCell *)rightCell imgView:(UIImageView *)iconView{

    UIImageView *imageV = [[UIImageView alloc]initWithImage:iconView.image];
    imageV.frame = iconView.frame;
    
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    CGPoint startPoint = [rightCell convertPoint:imageV.center toView:keyWindow];
    
    [keyWindow addSubview:imageV];
    
    //MARK:1.添加抛物线的动画
    //关键帧动画
    CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    //路径
    UIBezierPath *path = [UIBezierPath bezierPath];
    //起点
    [path moveToPoint:startPoint];
    //最高控制点
    CGPoint controlPoint = CGPointMake(startPoint.x + 50, startPoint.y - 50);
    //终点
    CGPoint endPoint = CGPointMake(kScreenWidth * 5 / 8, kScreenHeight - 30);
    //设置路径
    [path addQuadCurveToPoint:endPoint controlPoint:controlPoint];
    
    
    //把路径给帧动画
    keyAni.path = path.CGPath;
    //时长
    keyAni.duration = 0.5;
    
    CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    
    // 缩放倍数
    scaleAnimation.fromValue = @(1); // 开始时的倍率
    scaleAnimation.toValue = @(0.2); // 结束时的倍率
    
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    
    // 透明度
    opacityAnimation.fromValue = @(1); // 开始时 - 不透明
    opacityAnimation.toValue = @(0.4); // 结束时
    
    
    // 添加动画
    // 创建组动画
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[keyAni,scaleAnimation,opacityAnimation];
    group.duration = 0.5;
    
    group.delegate = self;
    
    [group setValue:imageV forKey:@"img"];
    // 添加给 imageV
    [imageV.layer addAnimation:group forKey:@"keyAni"];
    

    imageV.center = endPoint;
    imageV.alpha = 0;

}

//MARK:动画结束
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    UIImageView *imageV = (UIImageView *)[anim valueForKey:@"img"];
    
    [imageV removeFromSuperview];
    
}



// 设置界面
- (void)setupUI{

    // MARK: - bottomView
    // 创建底层 bottomview
    UIView *bottomView = [[UIView alloc]init];
    // 约束
    bottomView.frame = CGRectMake(0, kNaviHeight, kScreenWidth, kScreenHeight - kNaviHeight);
    // 添加到 控制器 的 view
    [self.view addSubview:bottomView];
    // 关联
    self.bottomView = bottomView;
    
    // MARK: - 创建 tableview
    [self setTableView];
    
    // 设置 lefttableview 的代理
    self.rightTableView.pushDelegate = self;
    
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    
    [self.view addGestureRecognizer:swipe];
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setTableView{

    // MARK: - 创建 lefttableview
    LBLeftTableView *leftTableView = [[LBLeftTableView alloc]init];
    [self.bottomView addSubview:leftTableView];
    
    // MARK: - 创建 righttableview
    LBRightTableView *rightTableView = [[LBRightTableView alloc]init];
    [self.bottomView addSubview:rightTableView];
    
    // MARK: - 约束
    [leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.bottom.equalTo(self.bottomView);
        make.width.mas_equalTo(1.0 * 90 / 375 * kScreenWidth);
    }];
    
    [rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.right.bottom.equalTo(self.bottomView);
        make.left.equalTo(leftTableView.mas_right);
    }];
    
    
    
    // 关联
    self.leftTableView = leftTableView;
    self.rightTableView = rightTableView;
    
    leftTableView.leftRow = self.leftRow;
    
    self.leftRow = 0;

}
#pragma mark - 加载数据
- (void)loadData{
    
    NSString *urlStr = @"supermarket.json.php";
    
    NSDictionary *dict = @{@"call":@"5"};
    
    // 获取模型数组
    [[LBGetDataTool sharedGetDatatool] getDataWithURLString:urlStr parameter:dict complete:^(NSArray *modelList, NSError *error, NSString *message) {
        if (modelList) {
            
            self.marketModelList = modelList;
            _isComplete = YES;
            // 设置界面
            [self setupUI];
            // 给两个 tableview 传数据
            self.leftTableView.marketModelList = modelList;
            self.rightTableView.marketModelList = modelList;
            // 停止菊花转动
            [SVProgressHUD dismiss];
            
        }else{
        
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [SVProgressHUD dismiss];
                [self errorAlert];
            });
        }
        
    }];
 
}

#pragma mark - 网络问题提示框
- (void)errorAlert{

    LBNotNetView *errorView = [LBNotNetView notNetView];
    [self.view addSubview:errorView];
    errorView.delegate = self;
    self.errorAlertView = errorView;
    
    
    [errorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(230);
        make.left.offset(80);
        make.right.offset(-80);
        make.height.mas_equalTo(170);
    }];
}

- (void)refreshWithNotNetView:(LBNotNetView *)notNetView{
    [self.errorAlertView removeFromSuperview];
    [SVProgressHUD showWithStatus:@"努力加载中..."];
    [self loadData];
}



// MARK: - push 到 详情页
// pushtodetailvc  的 delegate
- (void)pushToDetailVC:(LBRightTableView *)rightTableView withProductModel:(LBSuperMarketProducts *)model{
    
    LBSuperMarketDetailsVC *detailVC = [[LBSuperMarketDetailsVC alloc]init];
    // 传值
    detailVC.productModel = model;

    self.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:detailVC animated:YES];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


-(void)viewWillAppear:(BOOL)animated{
    
    if (!_isComplete) {
        // 菊花转
        [SVProgressHUD showWithStatus:@"努力加载中..."];
        
        [self.rightTableView reloadData];
    }

    // MARK: - 修改电池条状态
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    [self.rightTableView reloadData];
    

    self.navigationController.navigationBarHidden = YES;



    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    
        // 停止菊花转动
        [SVProgressHUD dismiss];
        
    
}



@end
